<?php

namespace app\admin\service;

use think\facade\Cache;
use think\facade\Request;

class WechatService
{
    private $config;

    public function __construct()
    {
        $this->config = config()['wechat'];
    }
    public function getAuthUrl($state)
    {
        $redirect = Request::root(true) . '/login/bind_wechat';

        return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->config['appid'] . '&redirect_uri='. urlencode($redirect). '&response_type=code&scope=snsapi_userinfo&state=' . $state . '#wechat_redirect';
    }

    public function getAuthAccessToken($code)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->config['appid'] . '&secret=' . $this->config['secret'] . '&code=' . $code . '&grant_type=authorization_code';
        return $this->request($url);
    }

    public function getUserInfo($accessToken, $openid) {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $accessToken . '&openid=' . $openid . '&lang=zh_CN';
        return $this->request($url);
    }

    public function sendTplMsg($param) {
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $this->getAccessToken(true);
        return $this->request($url, $param);
    }

    private function getAccessToken($force = false)
    {
        $token = Cache::get('wechat_access_token');
        if (!$token || $force) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->config['appid'] . '&secret=' . $this->config['secret'];
            $res = $this->request($url);
            $token = $res['access_token'];
            Cache::set('wechat_access_token', $token, 7000);
        }

        return $token;
    }

    private function request($url, $param = null)
    {
        $sendUrl = $url;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $sendUrl);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 300);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        if ($param) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($param));
            curl_setopt($curl, CURLOPT_POST, true);
        }
        $response = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($response, true);
        if (!empty($response['errcode'])) {
            throw new \Exception($response['errcode'] . ': ' . $response['errmsg'], $response['errcode']);
        }

        return $response;
    }
}